<script setup lang="ts">
import { ref } from 'vue'
import { FormInstance, Message } from '@arco-design/web-vue'
import { useRouter } from 'vue-router'
import { IconUser, IconLock, IconIdcard } from '@arco-design/web-vue/es/icon'
import { encrypt } from '@/utils/auth'
import { getPublicKeyUsingGet } from '@/api/authController'
import { userRegisterUsingPost } from '@/api/userController'

const router = useRouter()
const loading = ref(false)
const formRef = ref<FormInstance | null>(null)

const formData = ref({
  username: '',
  password: '',
  rePassword: '',
  nickname: '',
  name: ''
})

const successVisible = ref(false)
const successInfo = ref({
  username: '',
  password: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名' },
    { minLength: 8, message: '用户名长度不能小于8位' },
    { maxLength: 32, message: '用户名长度不能超过32位' }
  ],
  password: [
    { required: true, message: '请输入密码' },
    { minLength: 8, message: '密码长度不能小于8位' },
    { maxLength: 32, message: '密码长度不能超过32位' }
  ],
  rePassword: [
    { required: true, message: '请再次输入密码' },
    {
      validator: (value: string, callback: (error?: string) => void) => {
        if (value !== formData.value.password) {
          callback('两次输入的密码不一致')
        }
        callback()
      }
    }
  ],
  nickname: [
    { required: false, message: '请输入昵称' },
    { maxLength: 16, message: '昵称长度不能超过16位' }
  ],
  name: [
    { required: true, message: '请输入姓名' },
    { maxLength: 16, message: '姓名长度不能超过16位' }
  ]
}

const handleSubmit = async () => {
  if (!formRef.value) return
  const errors = await formRef.value.validate()
  if (errors) return

  loading.value = true
  try {
    // 1. 获取公钥加密密码
    const publicKey: any = await getPublicKeyUsingGet()
    const encryptedPassword = encrypt(formData.value.password, publicKey)
    const encryptedRePassword = encrypt(formData.value.rePassword, publicKey)

    // 2. 发送注册请求
    const res: any = await userRegisterUsingPost({
      ...formData.value,
      password: encryptedPassword,
      rePassword: encryptedRePassword
    })

    if (res?.code === 0) {
      // 保存注册成功的账号信息
      successInfo.value = {
        username: formData.value.username,
        password: formData.value.password
      }
      // 显示成功弹窗
      successVisible.value = true
      // 清空表单
      formData.value = {
        name: '',
        username: '',
        nickname: '',
        password: '',
        rePassword: ''
      }
    } else {
      Message.error(res?.message || '注册失败')
    }
  } catch (error) {
    Message.error('注册失败：' + error)
  } finally {
    loading.value = false
  }
}

// 处理弹窗关闭
const handleClose = () => {
  successVisible.value = false
}

// 处理去登录
const handleGoLogin = () => {
  successVisible.value = false
  router.push('/login')
}
const goToLogin = () => {
  router.push('/login')
}
const goToHelp = () => {
  router.push('/help')
}
</script>

<template>
  <div class="register-container">
    <div class="header">
      <div class="logo">极研协作</div>
    </div>

    <div class="register-box">
      <h1 class="title">注册极研协作</h1>

      <a-form
        :model="formData"
        @submit="handleSubmit"
        class="register-form"
        :rules="rules"
        ref="formRef"
      >
        <div class="form-header">
          <h2 class="form-title">账号注册</h2>
        </div>

        <a-form-item field="username" validate-trigger="blur">
          <a-input v-model="formData.username" placeholder="请输入用户名（8-32位）" allow-clear>
            <template #prefix>
              <icon-user />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item field="password" validate-trigger="blur">
          <a-input-password
            v-model="formData.password"
            placeholder="请输入密码（8-32位）"
            allow-clear
          >
            <template #prefix>
              <icon-lock />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item field="rePassword" validate-trigger="blur">
          <a-input-password v-model="formData.rePassword" placeholder="请再次输入密码" allow-clear>
            <template #prefix>
              <icon-lock />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item field="nickname" validate-trigger="blur">
          <a-input v-model="formData.nickname" placeholder="请输入昵称" allow-clear>
            <template #prefix>
              <icon-idcard />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item field="name" validate-trigger="blur">
          <a-input v-model="formData.name" placeholder="请输入姓名（不可更改）" allow-clear>
            <template #prefix>
              <icon-idcard />
            </template>
          </a-input>
        </a-form-item>

        <a-button type="primary" html-type="submit" long :loading="loading">注册</a-button>
      </a-form>

      <div class="footer-links">
        <a-link @click="goToLogin">返回登录</a-link>
        <a-link @click="goToHelp">帮助文档</a-link>
      </div>
    </div>
  </div>

  <!-- 注册成功弹窗 -->
  <a-modal
    v-model:visible="successVisible"
    :closable="false"
    :mask-closable="false"
    :footer="false"
    width="400px"
  >
    <template #title>
      <div class="success-title">
        <icon-check-circle-fill class="success-icon" />
        注册成功
      </div>
    </template>

    <div class="success-content">
      <p class="success-tip">请牢记以下登录信息：</p>
      <div class="info-item">
        <span class="label">账号：</span>
        <span class="value">{{ successInfo.username }}</span>
      </div>
      <div class="info-item">
        <span class="label">密码：</span>
        <span class="value">{{ successInfo.password }}</span>
      </div>
    </div>

    <div class="modal-footer">
      <a-space>
        <a-button @click="handleClose">取消</a-button>
        <a-button type="primary" @click="handleGoLogin">去登录</a-button>
      </a-space>
    </div>
  </a-modal>
</template>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px 0;
  background: #f6f8fa;
}

.header {
  margin-bottom: 40px;
}

.logo {
  font-size: 32px;
  font-weight: bold;
  color: #1a1a1a;
}

.register-box {
  width: 340px;
  padding: 16px;
}

.title {
  font-size: 24px;
  font-weight: 300;
  letter-spacing: -0.5px;
  text-align: center;
  margin-bottom: 20px;
}

.register-form {
  background: #fff;
  border: 1px solid #d0d7de;
  border-radius: 6px;
  padding: 20px;
  margin-bottom: 16px;
}

.form-header {
  margin-bottom: 16px;
  text-align: center;
}

.form-title {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
}

.footer-links {
  display: flex;
  justify-content: center;
  gap: 16px;
  font-size: 12px;
}

/* 成功弹窗样式 */
.success-title {
  display: flex;
  align-items: center;
  gap: 8px;
  color: rgb(var(--success-6));
  font-size: 16px;
  font-weight: 500;
}

.success-icon {
  font-size: 20px;
  color: rgb(var(--success-6));
}

.success-content {
  padding: 16px 0;
}

.success-tip {
  margin: 0 0 16px;
  color: var(--color-text-2);
}

.info-item {
  display: flex;
  margin-bottom: 12px;
  font-size: 14px;
  line-height: 22px;
}

.info-item .label {
  width: 60px;
  color: var(--color-text-3);
}

.info-item .value {
  color: var(--color-text-1);
  font-weight: 500;
}

.modal-footer {
  margin-top: 24px;
  text-align: right;
}

:deep(.arco-modal-header) {
  padding: 16px 20px;
  border-bottom: 1px solid var(--color-border);
}

:deep(.arco-modal-body) {
  padding: 20px;
}
</style>
